//
//  ControlTemplateViewEvaluateReplyController.m
//  Uhomebk
//
//  Created by Chiang on 2017/10/12.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ControlTemplateViewEvaluateReplyController.h"
#import "SoonAnswerViewController.h"

@interface ControlTemplateViewEvaluateReplyController ()<SoonAnswerViewControllerDelegate>{
    NSDictionary *initDict;
    UIButton *soonAnswer;//原因选择按钮
    UIView* lineView;//分割线
}

@end

@implementation ControlTemplateViewEvaluateReplyController

static ControlTemplateViewEvaluateReplyController *sharedManagerEvaluateReply = nil;
+ (ControlTemplateViewEvaluateReplyController *)sharedManagerEvaluateReply {
    sharedManagerEvaluateReply = [[self alloc] init];
    return sharedManagerEvaluateReply;
}

- (void)initVar
{
    _valueStr = @"0";
    _evaluateId = @"";
    _evaluateMessage = @"";
    _param_id = [SEGUtils ValueToString:[_params valueForKey:@"attrInstId"]];
    _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
    initDict = (NSDictionary *)[SEGUtils dictionaryWithJsonString:[_params valueForKey:@"initData"]];
    maxString = [[_params valueForKey:@"contentLengthLimit"] integerValue];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initVar];
    self.isNeedAdpterHotspot = YES;
    
    _bgMainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 195)];
    _bgMainView.backgroundColor = kColor_W;
    self.tempBgView = _bgMainView;
    [self.view addSubview:_bgMainView];
    
    UILabel* titleLabel = [[UILabel alloc] init];
    [titleLabel setText:[_params valueForKey:@"title"]];
    [titleLabel setFont:kFont_16];
    [titleLabel setTextColor:kColor_1];
    titleLabel.numberOfLines = 0;
    titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [_bgMainView addSubview:titleLabel];
    [titleLabel sizeToFit];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_bgMainView.mas_left).offset(HEADSPACE);
        make.top.equalTo(_bgMainView.mas_top).offset(HEADSPACE + 2);
        make.width.mas_equalTo(TITLE_WIDTH);
    }];
    
    UIView* classView = [[UIView alloc] initWithFrame:CGRectMake(CONTENTMARGIN_LEFT, 0, CGRectGetWidth(_bgMainView.bounds) - 102, 50)];
    classView.backgroundColor = kColor_W;
    [_bgMainView addSubview:classView];
    
    if ([[SEGUtils ValueToString:[_params valueForKey:@"readable"]] isEqualToString:@"0"]) {
        _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), 0);
    } else {
        //线条
        lineView = [[UIView alloc] initWithFrame:CGRectMake(LINEMARGIN_LEFT, CGRectGetHeight(_bgMainView.bounds) - 0.5, CGRectGetWidth(_bgMainView.bounds), 0.5)];
        lineView.backgroundColor = kColor_L2;
        lineView.tag  = 8888;
        [_bgMainView addSubview:lineView];
    }
    NSArray * initArray = initDict[@"evaluate"];
    NSString * attrValuestring = [_params valueForKey:@"attrValue"];
    NSDictionary *attrDic = [SEGUtils dictionaryWithJsonString:attrValuestring];
    //是否可写 0-不可写 1-可写
    if ([[SEGUtils ValueToString:[_params valueForKey:@"writable"]] isEqualToString:@"0"]) {
        _bgMainView.frame =CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, TEMPLATE_HEIGHT);
        if (attrDic) {
            UILabel* valueLabel = [[UILabel alloc] initWithFrame:CGRectMake(CONTENTMARGIN_LEFT, 0, CGRectGetWidth(_bgMainView.bounds) - CONTENTMARGIN_LEFT - CONTENTMARGIN_RIGHT, CGRectGetHeight(_bgMainView.bounds))];
            [valueLabel setFont:kFont_16];
            [valueLabel setTextColor:kColor_1];
            [valueLabel setText:attrDic[@"evaluate"]];
            [_bgMainView addSubview:valueLabel];
            NSDictionary *defaultValueDic = @{@"evaluate" : attrDic[@"evaluate"], @"message" : attrDic[@"message"]};
            _valueStr = [SEGUtils ValueToString:defaultValueDic];
        }
        
    } else {
        // 初始化评价
        _optional = @"0";
        BOOL isDefault = NO;
        UIImage *imagePre = [UIImage imageWithContentsOfFile:SEGPicName(@"greenStar")];
        UIImage *imageNor = [UIImage imageWithContentsOfFile:SEGPicName(@"grayStar")];
        NSString *defaultValue = @"";
        for (int i = 0; i < initArray.count; i++) {
            NSDictionary *dic = initArray[i];
            UIImageView* iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * (imagePre.size.width + 10), (50 - imagePre.size.height) / 2, imagePre.size.width, imagePre.size.height)];
            if (!isDefault) {
                [iconImageView setImage:imagePre];
            } else {
                [iconImageView setImage:imageNor];
            }
            if ([dic[@"isDefault"] intValue] == 1) {
                isDefault = YES;
                defaultValue = dic[@"id"];
            }
            [classView addSubview:iconImageView];
            CustomButtonView* abtn = [[CustomButtonView alloc] initWithFrame:CGRectMake(i * (imagePre.size.width + 10), 0, imagePre.size.width + 10, 50)];
            [abtn addTarget:self action:@selector(onBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            abtn.tag = 100 + i;
            [classView addSubview:abtn];
        }
        if (!isDefault) {
            for (UIImageView* aImageView in [_bgMainView.subviews objectAtIndex:1].subviews) {
                if ([aImageView isKindOfClass:[UIImageView class]]) {
                    [aImageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"grayStar")]];
                }
            }
        }
        UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 49.5, CGRectGetWidth(_bgMainView.frame), 0.5)];
        lineView1.backgroundColor = kColor_L2;
        [_bgMainView addSubview:lineView1];
        
        contentText = [[BaseTextView alloc] initWithFrame:CGRectMake( HEADSPACE - 5, 50, CGRectGetWidth(_bgMainView.frame)-2*HEADSPACE, 145-45)];
        [contentText setTextColor:kColor_1];
        [contentText setFont:kFont_16];
        [_bgMainView addSubview:contentText];
        contentText.delegate = self;
        
        if ([attrDic[@"evaluate"] integerValue] > 2) {
            //提示文本
            CGSize size = STRING_SIZE_FONT(CGRectGetWidth(contentText.bounds) - 10, [_params valueForKey:@"markedWords"], 16);
            msgLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, CGRectGetWidth(contentText.bounds) - 10, size.height)];
            msgLabel.lineBreakMode = NSLineBreakByCharWrapping;
            msgLabel.numberOfLines = 0;
            if ([_params valueForKey:@"markedWords"] && ![[_params valueForKey:@"markedWords"] isEqualToString:@""]) {
                [msgLabel setText:[_params valueForKey:@"markedWords"]];
            } else {
                [msgLabel setText:@"请输入内容"];
            }
            [msgLabel setFont:kFont_16];
            [msgLabel setTextColor:kColor_C];
            [contentText addSubview:msgLabel];
            
            contentText.inputAccessoryView = [self onKeyBoardFinishedButton];
            
            //快捷回复按钮
            soonAnswer = [UIButton buttonWithType:UIButtonTypeCustom];
            [soonAnswer setTitle:@"差评原因" forState:UIControlStateNormal];
            soonAnswer.titleLabel.font = kFont_12;
            soonAnswer.backgroundColor = kColor_T;
            soonAnswer.layer.cornerRadius = 9.5;
            soonAnswer.layer.masksToBounds = YES;
            soonAnswer.frame = CGRectMake(HEADSPACE, _bgMainView.bounds.size.height-2*HEADSPACE, 70, 19);
            [soonAnswer addTarget:self action:@selector(quickReplyAction) forControlEvents:UIControlEventTouchUpInside];
            [_bgMainView addSubview:soonAnswer];
            soonAnswer.hidden = NO;
            NSDictionary *dict = [SEGUtils dictionaryWithJsonString:_params[@"initData"]];
            
            if (![dict[@"message"] isKindOfClass:[NSArray class]] ||  [dict[@"message"] count] == 0) {
                soonAnswer.hidden = YES;
            }
            
            NSArray *initDataArray = [SEGUtils arrayWithJsonString:dict[@"message"]];
            if (initDataArray.count == 0) {
                soonAnswer.hidden = YES;
            }
        }
        
        NSDictionary *defaultValueDic = @{@"evaluate" : defaultValue, @"message" : @""};
        _valueStr = [SEGUtils ValueToString:defaultValueDic];
    }
}


//点击快捷回复
- (void)quickReplyAction {
    //类型查询
    SoonAnswerViewController *soonVC = [[SoonAnswerViewController alloc] init];
    soonVC.zk_delegate = self;
    soonVC.value = self.params[@"initData"];
    soonVC.typeStr = @"evaluate_reply";
    soonVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    soonVC.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    
    //设置弹出样式
    if (@available(iOS 8.0, *)) {
        soonVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    } else {
        soonVC.modalPresentationStyle = UIModalPresentationCurrentContext;
    }
    [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:soonVC animated:YES completion:^{
        //
    }];
    
}
- (void)onBtnAction:(CustomButtonView*)sender {
    if (sender.tag - 100 > 2) {
        _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), 50);
        contentText.hidden = YES;
        soonAnswer.hidden = YES;
    } else {
        _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), 195);
        contentText.hidden = NO;
        soonAnswer.hidden = NO;
    }
    lineView.frame = CGRectMake(15, CGRectGetHeight(_bgMainView.bounds) - 0.5, CGRectGetWidth(_bgMainView.bounds), 0.5);
    
    int i = 100;
    for (UIImageView* aImageView in [_bgMainView.subviews objectAtIndex:1].subviews) {
        if ([aImageView isKindOfClass:[UIImageView class]]) {
            UIImage* image = nil;
            if (i <= sender.tag) {
                image = [UIImage imageWithContentsOfFile:SEGPicName(@"greenStar")];
            } else {
                image = [UIImage imageWithContentsOfFile:SEGPicName(@"grayStar")];
            }
            i++;
            [aImageView setImage:image];
        }
    }
    NSArray * valueArray = initDict[@"evaluate"];
    NSDictionary* valueStr2 = [valueArray objectAtIndex:(int)sender.tag - 100];
    _evaluateId = valueStr2[@"id"];
    _optional = @"0";
    
    NSDictionary *defaultValueDic = @{@"evaluate" : _evaluateId, @"message" : _evaluateMessage};
    _valueStr = [SEGUtils ValueToString:defaultValueDic];
    
    if (_evaluateReplyDelegate) {
        [self.evaluateReplyDelegate onFeeRefeshUI];
    }
}

/**
 *  给评论控件填充值
 */
- (void)paddingEvaluateReply:(NSString*)valueStr
{
    if ([_params[@"initData"] length] == 0) {
        return;
    }
    NSDictionary *attrDic = [SEGUtils dictionaryWithJsonString:valueStr];
    contentText.text = attrDic[@"message"];
    if ([_valueStr length] > 0) {
        UIView* aview = [_bgMainView.subviews objectAtIndex:1];
        for (int i = 0; i < [SEGUtils ValueToInteger:attrDic[@"evaluate"]]; i++) {
            if (aview.subviews.count == 0) {
                return;
            }
            UIView *bView = [aview.subviews objectAtIndex:i];
            if ([bView isKindOfClass:[UIImageView class]]) {
                UIImageView* aimageView = (UIImageView *)bView;
                [aimageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"greenStar")]];
            }
        }
        _optional = @"0";
    } else {
        _optional = @"1";
    }
}

/**
 *  收键盘
 */
- (void)onKeyBoardFinishedButton:(CustomButtonView*)sender {
    [contentText resignFirstResponder];
    //    NSLog(@"键盘收起时多行文本框高度 %@",NSStringFromCGRect(_bgMainView.bounds));
}

- (void)textViewDidBeginEditing:(UITextView*)textView {
    //    NSLog(@"开始编辑时文本框高度 %@",NSStringFromCGRect(textView.bounds));
    [[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardDidShowNotification object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:textView, @"object", nil]];
}
- (void)textViewDidEndEditing:(UITextView*)textView {
    
    //     NSLog(@"结束编辑时文本框高度 %@",NSStringFromCGRect(textView.bounds));
    [[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardDidHideNotification object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:textView, @"object", nil]];
}

/**
 *  当多行文本内容有变化，进行回调
 *  @param textView 文本实例
 */
- (void)textViewDidChange:(BaseTextView*)textView {
    if ([[textView text] length] > 0) {
        [msgLabel setHidden:YES];
        _optional = @"0";
        _evaluateMessage = [textView text];
    } else {
        [msgLabel setHidden:NO];
        _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
        _evaluateMessage = @"";
    }
    if ([[textView text] length] > maxString) {
        NSString* contentStr = [[textView text] substringToIndex:maxString];
        textView.text = contentStr;
    }
    _evaluateMessage = [textView text];
}

/**
 *  当多行文本内容快要结束时，进行回调
 *  @return 返回YES值
 */
- (BOOL)textViewShouldEndEditing:(BaseTextView*)textView {
    NSDictionary *defaultValueDic = @{@"evaluate" : _evaluateId, @"message" : _evaluateMessage};
    _valueStr = [SEGUtils ValueToString:defaultValueDic];
    [contentText resignFirstResponder];
    return YES;
}

//选择完快捷语句回调
- (void)SelectSoonAnswerFinished:(id)data {
    NSString *answerStr = data;
    //如果有填写 可以进行提交
    if (answerStr.length > 0) {
        [msgLabel setHidden:YES];
        contentText.text = answerStr;
        _optional = @"0";
    } else {
        [msgLabel setHidden:NO];
        _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
    }
    _evaluateMessage = answerStr;
    NSDictionary *defaultValueDic = @{@"evaluate" : _evaluateId, @"message" : _evaluateMessage};
    _valueStr = [SEGUtils ValueToString:defaultValueDic];
}
@end

